package com.zsk.shop.service;

import com.alibaba.fastjson.JSONObject;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.enums.SmsEnum;
import com.zsk.shop.common.utils.SmsUtil;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.ShopUser;
import com.zsk.shop.enums.EnumDecodeType;
import com.zsk.shop.enums.EnumLoginPlatform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author ljh
 * @date 2018年2月28日 下午3:23:01
 */
@Component
public class SmsService {

    private final static Logger logger = LoggerFactory.getLogger(SmsService.class);

    @Resource
    private SmsUtil smsUtil;

    @Resource
    private ShopUserService shopUserService;
    @Resource
    private DataDictionaryService dataDictionaryService;

    @Resource
    private VerificationCodeService verificationCodeService;

    @Resource
    private VerificationImageService verificationImageService;

    @Transactional(rollbackFor = {Exception.class})
    public BaseResponse send(String mobile, SmsEnum data, String[] arr) {
        JSONObject jsonObject = new JSONObject();
        if (arr != null) {
            jsonObject.put("code", arr[0]);
            jsonObject.put("tip", arr[0]);
            if (arr.length > 1) {
                jsonObject.put("name", arr[1]);
            }
            if (arr.length > 2) {
                jsonObject.put("time", arr[2]);
            }
        }
        String phone = mobile;
        String templateCode = data.getCode();
        try {
            logger.info("开始发送短信,{},{},{}", phone, data.getContent(), arr);
            return smsUtil.send(phone, templateCode, jsonObject);
        } catch (Exception e) {
            logger.info("发送短信失败,{},{},{}", phone, data.getContent(), arr);
            e.printStackTrace();
            return BaseResponse.error("发送短信失败");
        }
    }

    /**
     * 请求发送验证码
     *
     * @param id
     * @param result
     * @param type
     * @param decodeType type = 2时，需要校验绑定账号对应数据是否存在，如果有则不发送短信
     * @param phone
     * @return
     */
    public BaseResponse askSendSms(String id, String result, Integer type, Integer decodeType, String phone, Integer clientType) {
        if (ToolUtil.isOneEmpty(type, phone)) {
            return BaseResponse.error("缺失必填参数");
        }
        String str = verificationImageService.checkVerificationImage(Long.parseLong(id), result);
        if (ToolUtil.isNotEmpty(str)) {
            return BaseResponse.error(str);
        }
        //校验发送频率
        if (verificationCodeService.overLimit(phone)) {
            return BaseResponse.error("当前手机号发送频率超限，请稍后再试！");
        }
        //注册，手机号存在则不发送
        if (type.equals(SmsEnum.REG.getId())) {
            //校验手机号是否被注册
            ShopUser user = shopUserService.queryTrueUserByPhone(phone);
            if (ToolUtil.isNotEmpty(user)) {
                return BaseResponse.error("当前手机账号已注册");
            }
        }
        if (type.equals(SmsEnum.BING_PHONE.getId())) {
            if (ToolUtil.isEmpty(decodeType)) {
                return BaseResponse.error("当前服务异常");
            }
            //校验手机号是否被注册
            ShopUser user = shopUserService.queryTrueUserByPhone(phone);
            if (ToolUtil.isNotEmpty(user)) {
                //如果是微信，如果是钉钉，如果是QQ
                if (decodeType.equals(EnumDecodeType.WECHAT.getCode())) {
                    if (clientType.equals(EnumLoginPlatform.IOS.getCode()) && ToolUtil.isNotEmpty(user.getWxMiniOpenId())) {
                        return BaseResponse.error("当前手机账号已注册且绑定过微信,不能再被绑定");
                    }
                } else if (decodeType.equals(EnumDecodeType.DING.getCode())) {
//                    if (ToolUtil.isNotEmpty(user.getDingOpenId())) {
//                        return BaseResponse.error("当前手机账号已注册且绑定过钉钉,不能再被绑定");
//                    }
                } else if (decodeType.equals(EnumDecodeType.QQ.getCode())) {
//                    if (clientType.equals(EnumLoginPlatform.IOS.getCode()) && ToolUtil.isNotEmpty(user.getQqOpenId())) {
//                        return BaseResponse.error("当前手机账号已注册且绑定过QQ,不能再被绑定");
//                    }
                } else if (decodeType.equals(EnumDecodeType.APPLE.getCode())) {
//                    if (ToolUtil.isNotEmpty(user.getAppleSub())) {
//                        return BaseResponse.error("当前手机账号已注册且绑定过APPLE ID,不能再被绑定");
//                    }
                }
            }
        }
        if (type.equals(SmsEnum.CHANGE_PWD.getId())) {
            //找回密码
            //校验手机号是否被注册
            ShopUser user = shopUserService.queryTrueUserByPhone(phone);
            if (ToolUtil.isEmpty(user)) {
                return BaseResponse.error("该手机号暂未注册");
            }
        }
        if (type.equals(SmsEnum.LOGIN_REG.getId())) {
            //登录/注册相关
        }
        //生成验证码
        String code = VerificationCodeService.genCode();
        //保存数据
        this.verificationCodeService.insertCode(code, phone, type);
        //发送
        SmsEnum smsEnum = SmsEnum.getById(type);
        if (ToolUtil.isEmpty(smsEnum)) {
            logger.error("短信模板有误，发送短信失败");
            return BaseResponse.error("系统错误");
        }
        return this.send(phone, smsEnum, new String[]{code});
    }

    /**
     * 请求发送验证码
     *
     * @param id
     * @param result
     * @param type
     * @param decodeType type = 2时，需要校验绑定账号对应数据是否存在，如果有则不发送短信
     * @param phone
     * @return
     */
    public BaseResponse h5AskSendSms(String id, String result, Integer type, Integer decodeType, String phone, Integer clientType) {
        if (ToolUtil.isOneEmpty(type, phone)) {
            return BaseResponse.error("缺失必填参数", "500");
        }
        Map<String, String> map = verificationImageService.h5CheckVerificationImage(Long.parseLong(id), result);
        if (ToolUtil.isNotEmpty(map)) {
            return BaseResponse.error(map.get("value"), map.get("key"));
        }
        //校验发送频率
        if (verificationCodeService.overLimit(phone)) {
            return BaseResponse.error("当前手机号发送频率超限，请稍后再试！", "504");
        }
        //注册，手机号存在则不发送
        if (type.equals(SmsEnum.REG.getId())) {
            //校验手机号是否被注册
            ShopUser user = shopUserService.queryTrueUserByPhone(phone);
            if (ToolUtil.isNotEmpty(user)) {
                return BaseResponse.error("当前手机账号已注册", "505");
            }
        }
        if (type.equals(SmsEnum.BING_PHONE.getId())) {
            if (ToolUtil.isEmpty(decodeType)) {
                return BaseResponse.error("当前服务异常", "500");
            }
            //校验手机号是否被注册
            ShopUser user = shopUserService.queryTrueUserByPhone(phone);
            if (ToolUtil.isNotEmpty(user)) {
                //如果是微信，如果是钉钉，如果是QQ
                if (decodeType.equals(EnumDecodeType.WECHAT.getCode())) {
                    if (clientType.equals(EnumLoginPlatform.IOS.getCode()) && ToolUtil.isNotEmpty(user.getWxMiniOpenId())) {
                        return BaseResponse.error("当前手机账号已注册且绑定过微信,不能再被绑定", "506");
                    }
                } else if (decodeType.equals(EnumDecodeType.DING.getCode())) {
//                    if (ToolUtil.isNotEmpty(user.getDingOpenId())) {
//                        return BaseResponse.error("当前手机账号已注册且绑定过钉钉,不能再被绑定");
//                    }
                } else if (decodeType.equals(EnumDecodeType.QQ.getCode())) {
//                    if (clientType.equals(EnumLoginPlatform.IOS.getCode()) && ToolUtil.isNotEmpty(user.getQqOpenId())) {
//                        return BaseResponse.error("当前手机账号已注册且绑定过QQ,不能再被绑定");
//                    }
                } else if (decodeType.equals(EnumDecodeType.APPLE.getCode())) {
//                    if (ToolUtil.isNotEmpty(user.getAppleSub())) {
//                        return BaseResponse.error("当前手机账号已注册且绑定过APPLE ID,不能再被绑定");
//                    }
                }
            }
        }
        if (type.equals(SmsEnum.CHANGE_PWD.getId())) {
            //找回密码
            //校验手机号是否被注册
            ShopUser user = shopUserService.queryTrueUserByPhone(phone);
            if (ToolUtil.isEmpty(user)) {
                return BaseResponse.error("该手机号暂未注册", "500");
            }
        }
        if (type.equals(SmsEnum.LOGIN_REG.getId())) {
            //登录/注册相关
        }
        //生成验证码
        String code = VerificationCodeService.genCode();
        //保存数据
        this.verificationCodeService.insertCode(code, phone, type);
        //发送
        SmsEnum smsEnum = SmsEnum.getById(type);
        if (ToolUtil.isEmpty(smsEnum)) {
            logger.error("短信模板有误，发送短信失败");
            return BaseResponse.error("系统错误", 506);
        }
        return this.send(phone, smsEnum, new String[]{code});
    }

    public BaseResponse askCheckSms(Integer type, String phone, String code) {
        Boolean isTrue = verificationCodeService.checkCode(phone, type, code);
        if (isTrue) {
            return BaseResponse.success(isTrue);
        } else {
            return BaseResponse.error("验证码校验失败");
        }
    }

    public BaseResponse askSendFinanceSms() {
        String phone = dataDictionaryService.getValueStrByKey("ASK_FINANCE_PHONES");
        if (ToolUtil.isEmpty(phone)) {
            return BaseResponse.error("");
        }
        //发送
        SmsEnum smsEnum = SmsEnum.getById(SmsEnum.ASK_FINANCE_USER_WITHDRAW.getId());
        if (ToolUtil.isEmpty(smsEnum)) {
            logger.error("短信模板有误，发送短信失败");
            return BaseResponse.error("系统错误");
        }
        return this.send(phone, smsEnum, null);
    }

}
